import express from "express";
import MySQLPool from '../mysqlCreatePool';
import axios from "axios";
import { appid, jwtSecretKey, secret } from "../server.config";
import jwt from 'jsonwebtoken'
import { getuserinfo } from "../sqlstring";
const router = express.Router();
const db = new MySQLPool();
// 获取奖惩类型字典
router.post("/", async (req: any, res: any) => {
  console.log('aaa1', req.body.code)
  const js_code = req.body.code ?? ""
  try {
    const re = await axios.get(`https://api.weixin.qq.com/sns/jscode2session?js_code=${js_code}&appid=${appid}&secret=${secret}&grant_type=authorization_code`)
    if (re.status === 200) {
      const { openid } = re.data
      const sql = `CALL CreateUser('${openid}');`
      const [sqlres] = await db.queryRows(sql)
      if (sqlres[0].length) {
        const user = sqlres[0][0]
        const token = jwt.sign({ id: user.id, nickname: user.nickname, role: user.role }, jwtSecretKey)
        delete user.openid
        res.send({
          code: 200,
          message: '',
          data: {
            user,
            token
          },
        });
      }
      else {
        res.send({
          code: 201,
          message: '登录失败',
          data: null,
        });
      }
    }
    else {
      res.send({
        code: 201,
        message: '没数据',
        data: null,
      });
    }
  } catch (e) {
    res.send({
      code: 201,
      message: e,
      data: null,
    });
  }
});
export default router
